<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />

        <!-- 统计卡片 -->
        <div class="statistics-cards" style="margin-bottom: 20px;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #409eff;">
                                <el-icon><User /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.totalUsers || 0 }}</div>
                                <div class="stat-label">总用户数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #67c23a;">
                                <el-icon><Star /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.managers || 0 }}</div>
                                <div class="stat-label">店长数量</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="6">
                    <el-card shadow="hover" class="stat-card">
                        <div class="stat-content">
                            <div class="stat-icon" style="background: #e6a23c;">
                                <el-icon><User /></el-icon>
                            </div>
                            <div class="stat-info">
                                <div class="stat-number">{{ statistics.members || 0 }}</div>
                                <div class="stat-label">会员总数</div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                
            </el-row>
        </div>

        <!-- 表格顶部菜单 -->
        <TableHeader
            :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('linkage.relation.quick Search Fields') })"
        >
            <template #buttonsLeft>
                <el-button type="primary" @click="exportData">
                    <el-icon><Download /></el-icon>
                    导出数据
                </el-button>
                <el-button type="success" @click="showTeamTree">
                    <el-icon><Share /></el-icon>
                    团队树形图
                </el-button>
                <el-select v-model="userTypeFilter" placeholder="筛选用户类型" clearable style="width: 150px; margin-left: 10px;" @change="filterByUserType">
                    <el-option label="全部" value="" />
                    <el-option label="无状态" value="0" />
                    <el-option label="分红线用户" value="1" />
                    <el-option label="财富线用户" value="2" />
                </el-select>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <Table ref="tableRef"></Table>

        <!-- 表单 -->
        <PopupForm />

        <!-- 团队树形图弹窗 -->
        <el-dialog v-model="teamTreeVisible" title="团队树形图" width="80%" :close-on-click-modal="false">
            <div class="team-tree-container" style="height: 500px; overflow: auto;">
                <el-tree
                    :data="teamTreeData"
                    :props="treeProps"
                    node-key="id"
                    default-expand-all
                    :expand-on-click-node="false"
                >
                    <template #default="{ node, data }">
                        <div class="tree-node">
                            <el-avatar :size="32" :src="data.avatar || '/static/images/avatar.png'" />
                            <span class="node-info">
                                <div class="node-name">{{ data.nickname || data.username }}</div>
                                <div class="node-details">
                                    <el-tag size="small" :type="data.level === 2 ? 'success' : data.level === 1 ? 'info' : 'warning'">
                                        {{ data.level === 2 ? '店长' : data.level === 1 ? '会员' : '新用户' }}
                                    </el-tag>
                                    <span class="node-count">团队: {{ data.team_count || 0 }} | 直推: {{ data.direct_count || 0 }}</span>
                                </div>
                            </span>
                        </div>
                    </template>
                </el-tree>
            </div>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { onMounted, provide, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { User, Star, Connection, TrendCharts, Download, Share, Trophy } from '@element-plus/icons-vue'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'

defineOptions({
    name: 'linkage/relation',
})

const { t } = useI18n()
const tableRef = ref()
const teamTreeVisible = ref(false)
const teamTreeData = ref([])
const userTypeFilter = ref('')
const statistics = reactive({
    totalUsers: 0,
    managers: 0,
    members: 0
})

// 自定义操作按钮
const optButtons: OptButton[] = [
    ...defaultOptButtons(['edit', 'delete']),
    // {
    //     render: 'tipButton',
    //     name: 'team',
    //     title: '查看团队',
    //     text: '',
    //     type: 'success',
    //     icon: 'fa fa-users',
    //     click: (row: any) => {
    //         showUserTeam(row.user_id)
    //     }
    // },
    // {
    //     render: 'tipButton',
    //     name: 'upgrade',
    //     title: '升级店长',
    //     text: '',
    //     type: 'warning',
    //     icon: 'fa fa-star',
    //     click: (row: any) => {
    //         upgradeToManager(row.user_id)
    //     }
    // }
]

const treeProps = {
    children: 'children',
    label: 'nickname'
}

/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/linkage.Relation/'),
    {
        pk: 'id',
        column: [
            { type: 'selection', align: 'center', operator: false },
            { label: t('linkage.relation.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
            { 
                label: '用户信息', 
                prop: 'user.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '邀请人', 
                prop: 'parent.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '根节点店长', 
                prop: 'root.nickname', 
                align: 'center', 
                width: 200
            },
            { 
                label: '等级', 
                prop: 'level', 
                align: 'center', 
                width: 100,
                render: 'tag',
                replaceValue: { '0': '新用户', '1': '会员', '2': '店长' },
                custom: { '0': 'warning', '1': 'info', '2': 'success' }
            },
            { 
                label: '用户类型', 
                prop: 'user_type', 
                align: 'center', 
                width: 120,
                render: 'tag',
                replaceValue: { '0': '无状态', '1': '分红线', '2': '财富线' },
                custom: { '0': 'info', '1': 'warning', '2': 'primary' },
                operator: '=',
                sortable: 'custom'
            },
            { 
                label: '团队统计', 
                prop: 'team_count', 
                align: 'center', 
                width: 150
            },
            { 
                label: '直推统计', 
                prop: 'direct_count', 
                align: 'center', 
                width: 150
            },
            { 
                label: '状态', 
                prop: 'status', 
                align: 'center', 
                width: 100,
                render: 'tag',
                replaceValue: { '1': '正常', '0': '冻结' },
                custom: { '1': 'success', '0': 'danger' }
            },
            { 
                label: '创建时间', 
                prop: 'create_time', 
                align: 'center', 
                render: 'datetime', 
                operator: 'RANGE', 
                sortable: 'custom', 
                width: 160, 
                timeFormat: 'yyyy-mm-dd hh:MM:ss' 
            },
            { label: t('Operate'), align: 'center', width: 150, render: 'buttons', buttons: optButtons, operator: false },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: { parent_id: null, root_id: null, level: 0, user_type: 0, team_count: 0, direct_count: 0, status: '1' },
    }
)

provide('baTable', baTable)

// 获取统计数据
const getStatistics = async () => {
    try {
        // 直接调用 API 获取数据，而不是通过 baTable.onTableHeaderAction
        const response: any = await baTable.api.index(baTable.table.filter)
        if (response && response.data) {
            const data = response.data
            
            // 使用 Object.assign 确保响应式更新
            Object.assign(statistics, {
                totalUsers: data.totalUsers || 0,
                managers: data.managers || 0,
                members: data.members || 0
            });
        }
    } catch (error) {
        console.error('获取统计数据失败:', error)
    }
}

// 导出数据
const exportData = () => {
    ElMessage.success('导出功能开发中...')
}

// 显示团队树形图
const showTeamTree = () => {
    teamTreeVisible.value = true
    // 这里可以调用API获取团队树形数据
    loadTeamTreeData()
}

// 加载团队树形数据
const loadTeamTreeData = async () => {
    try {
        // 这里应该调用后端API获取团队树形数据
        // const response = await fetch('/admin/linkage.Relation/teamTree')
        // teamTreeData.value = response.data
        
        // 临时数据
        teamTreeData.value = []
    } catch (error) {
        console.error('加载团队树形数据失败:', error)
    }
}

// 查看用户团队
const showUserTeam = (userId: number) => {
    ElMessage.info(`查看用户 ${userId} 的团队`)
}

// 升级为店长
const upgradeToManager = async (userId: number) => {
    try {
        // 这里应该调用后端API升级用户为店长
        // await fetch(`/admin/linkage.Relation/upgrade/${userId}`, { method: 'POST' })
        ElMessage.success('升级成功')
        baTable.onTableHeaderAction('refresh')
    } catch (error) {
        ElMessage.error('升级失败')
    }
}

// 按用户类型筛选
const filterByUserType = () => {
    if (userTypeFilter.value === '') {
        // 清除筛选
        baTable.table.filter = {}
    } else {
        // 设置筛选条件
        baTable.table.filter = {
            user_type: userTypeFilter.value
        }
    }
    baTable.onTableHeaderAction('refresh')
}

onMounted(async () => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    
    // 先等待表格数据加载完成
    await baTable.getIndex()
    
    // 然后初始化排序和拖拽
    baTable.initSort()
    baTable.dragSort()
    
    // 最后获取统计数据（避免重复请求）
    await getStatistics()
})
</script>

<style scoped lang="scss">
.statistics-cards {
    .stat-card {
        .stat-content {
            display: flex;
            align-items: center;
            gap: 16px;
            
            .stat-icon {
                width: 48px;
                height: 48px;
                border-radius: 8px;
                display: flex;
                align-items: center;
                justify-content: center;
                color: white;
                font-size: 20px;
            }
            
            .stat-info {
                flex: 1;
                
                .stat-number {
                    font-size: 24px;
                    font-weight: bold;
                    color: #303133;
                    line-height: 1;
                }
                
                .stat-label {
                    font-size: 14px;
                    color: #909399;
                    margin-top: 4px;
                }
            }
        }
    }
}

.team-tree-container {
    .tree-node {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 4px 0;
        
        .node-info {
            flex: 1;
            
            .node-name {
                font-weight: bold;
                margin-bottom: 2px;
            }
            
            .node-details {
                display: flex;
                align-items: center;
                gap: 8px;
                
                .node-count {
                    font-size: 12px;
                    color: #999;
                }
            }
        }
    }
}
</style>
